package com.gxa.component.aspect;

import com.gxa.annotation.Log;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Arrays;

@Component
@Aspect
public class LogAspect {


    @Around("@annotation(com.gxa.annotation.Log)")
    public Object around(ProceedingJoinPoint point) throws Throwable {

        long beginTime = System.currentTimeMillis();
        //执行业务方法
        Object result = point.proceed();
        //执行时长(毫秒)
        long time = System.currentTimeMillis() - beginTime;

        //保存日志
        saveSysLog(point, time);

        return result;
    }

    private void saveSysLog(ProceedingJoinPoint joinPoint, long time) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();

        Log syslog = method.getAnnotation(Log.class);
        if(syslog != null){
            //请求的方法名
            String className = joinPoint.getTarget().getClass().getName();
            String methodName = signature.getName();

            //请求的参数
            Object[] args = joinPoint.getArgs();
            try{
                //调用数据库保存
                System.out.println("类--->" + className +",方法----->" + methodName + ",参数-->" + Arrays.toString(args)+time/100);
            }catch (Exception e){
                e.printStackTrace();
                //抛异常
            }
        }

    }
}